package com.pai4j.api.filter;
import com.pai4j.common.bean.PAIResponseBean;
import com.pai4j.common.bean.PAIResponseBeanUtil;
import com.pai4j.common.exception.AuthException;
import com.pai4j.remote.user.AccessApplicationServiceClient;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author: 程序员七七
 * @Date: 16.11.21 11:26 下午
 */
@Slf4j
@Order(-6)
@WebFilter(filterName = "oauthFilter", urlPatterns = {"/api/*"})
@Component
public class ApiAuthFilter implements Filter {

    @Autowired
    private AccessApplicationServiceClient accessApplicationServiceClient;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String ak = request.getHeader("access-key");
        String sk = request.getHeader("secret-key");
        if (StringUtils.isBlank(ak) || StringUtils.isBlank(sk)) {
            throw new AuthException("无权限");
        }
        PAIResponseBean<Boolean> apiResponseBean = accessApplicationServiceClient.checkAkSk(ak, sk);
        if (PAIResponseBeanUtil.isOk(apiResponseBean) && ObjectUtils.equals(true, apiResponseBean.getData())) {
            filterChain.doFilter(request, servletResponse);
            return;
        }
        throw new AuthException("无权限");
    }

    @Override
    public void destroy() {

    }
}
